package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {


    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;


    /**
     * 保存本地交易记录
     *
     * @param paymentType 微信的充值或者交易
     * @param orderNo     订单的编号
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo) {
        //1.获取交易是否已经存在
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(
                new LambdaQueryWrapper<PaymentInfo>()
                        .eq(PaymentInfo::getOrderNo, orderNo)
                        .eq(PaymentInfo::getPaymentType, paymentType)
        );
        if (paymentInfo != null) {
            return paymentInfo;
        }
        paymentInfo = new PaymentInfo();
        //2.保存订单的账户充值信息 支付类型：1301-订单 1302-充值
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            Assert.notNull(orderInfo, "订单不存在");
            if (SystemConstant.ORDER_STATUS_CANCEL.equals(orderInfo.getOrderStatus())) {
                throw new GuiguException(500, "订单已经取消");
            }
            paymentInfo.setPaymentType(paymentType);
            paymentInfo.setAmount(orderInfo.getOrderAmount());
            paymentInfo.setPaymentType(SystemConstant.PAYMENT_TYPE_ORDER);
            paymentInfo.setUserId(orderInfo.getUserId());
            paymentInfo.setContent(orderInfo.getOrderTitle());

        }

        //3.保存用户的的账户充值信息
        if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            Assert.notNull(rechargeInfo, "订单不存在");

            if (SystemConstant.ORDER_STATUS_CANCEL.equals(rechargeInfo.getRechargeStatus())) {
                throw new GuiguException(500, "订单已经取消");
            }
            paymentInfo.setUserId(rechargeInfo.getUserId());
            paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfo.setContent(paymentType);
        }
        //4.封装数据 保存订单的账户充值信息和交易信息
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        paymentInfo.setEpaymentStatus(SystemConstant.ORDER_STATUS_UNPAID);
//        paymentInfo.setOutTradeNo();
//        paymentInfo.setCallbackTime();
//        paymentInfo.setCallbackContent();
        //3.保存订单的交易信息 创建一个交易记录
        paymentInfoMapper.insert(paymentInfo);
        return paymentInfo;
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void updatePaymentInfo(Transaction transaction) {
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(
                new LambdaQueryWrapper<PaymentInfo>()
                        .eq(PaymentInfo::getOrderNo, transaction.getOutTradeNo()));

        paymentInfo.setOrderNo(transaction.getOutTradeNo());
        paymentInfo.setOutTradeNo(transaction.getOutTradeNo());
        paymentInfo.setEpaymentStatus(SystemConstant.ORDER_STATUS_PAID);
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(transaction.toString());

        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentInfo.getPaymentType())) {
            Result result = orderFeignClient.orderPaySuccess(transaction.getOutTradeNo());
            if (result.getCode().intValue() != 200) {
                throw new GuiguException(500, "支付失败");
            }
            paymentInfo.setPaymentType(SystemConstant.PAYMENT_TYPE_ORDER);
        }

        if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentInfo.getPaymentType())) {
            Result result = accountFeignClient.rechargePaySuccess(transaction.getOutTradeNo());
            if (result.getCode().intValue() != 200) {
                throw new GuiguException(500, "支付失败");
            }
            paymentInfo.setPaymentType(SystemConstant.PAYMENT_TYPE_ORDER);
        }
        paymentInfoMapper.updateById(paymentInfo);
    }
}
